import cv2
import os


def combine_video(source_path, video_list, video_name, save_fourcc_format='mp4v'):
    # video_list = os.listdir(source_path)
    target_video = os.path.join(source_path, video_name)
    video_file = os.path.join(source_path, video_list[0])

    cap = cv2.VideoCapture(video_file)
    f_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    f_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    f_shape = (int(f_width), int(f_height))
    fps = cap.get(cv2.CAP_PROP_FPS)
    four_cc = cv2.VideoWriter_fourcc(*save_fourcc_format)

    video_writer = cv2.VideoWriter(target_video, four_cc, fps, f_shape)
    for video in video_list:
        video_file = os.path.join(source_path, video)
        cap = cv2.VideoCapture(video_file)
        if cap.isOpened():
            print("Start to combine %s" % video)
            frame_num = 1
            while True:
                _, frame = cap.read()
                if frame is not None:
                    video_writer.write(frame)
                    # print("Start to combine number %s frame" % frame_num)
                    frame_num += 1
                else:
                    break
            cap.release()
        else:
            print("%s opened failed !" % video_file)
            continue
    video_writer.release()


if __name__ == "__main__":
    root_path = r"/home/kaijia/algo-env/Utils/sample/223A/video_fragment"
    # video_list = sorted(os.listdir(root_path))
    video_list = []

    files_and_creation_times = [(f, os.path.getctime(os.path.join(root_path, f))) for f in os.listdir(root_path)]
    sorted_files = sorted(files_and_creation_times, key=lambda x: x[1])
    #
    # 输出排序后的文件名
    for file_name, creation_time in sorted_files:
        # print(file_name)
        video_list.append(file_name)
    print(video_list)
    combine_video(root_path, video_list, video_name="223A_B737_02.mp4")
